<script setup lang="ts">
import { ref, onMounted, watch, defineProps, nextTick, onUnmounted } from 'vue';
import { LocateSetData } from '@/utils/appCommon/appCommonOptions/aeLocateConfigModel';
import * as PIXI from 'pixi.js';

// 定义接收的props
const props = defineProps<{
  locateSetting: LocateSetData;
  renderParams: {
    width: number;
    height: number;
    viewMode: number;
  };
  searchParams: any;
}>();

// PIXI相关引用
let app: PIXI.Application | null = null;
let container: PIXI.Container | null = null;
const gridSize = 10; // 10x10网格
const padding = 50; // 内边距50px
// 存储图形元素，直接使用DisplayObject类型
const objects = ref<Array<{ longitude: number; latitude: number; type: 'sensor' | 'point'; graphic: PIXI.DisplayObject; label?: PIXI.Text; tooltip?: PIXI.Container; id?: number }>>([]);
// 传感器编号计数器
let sensorCounter = 1;

// 计算网格单元大小
const calculateGridSize = () => {
  const availableWidth = props.renderParams.width - 2 * padding;
  const availableHeight = props.renderParams.height - 2 * padding;
  const cellWidth = availableWidth / gridSize;
  const cellHeight = availableHeight / gridSize;
  return { cellWidth, cellHeight };
};

// 初始化PIXI应用
const initPIXI = () => {
  console.log("initPIXI")
  if (app) {
    app.destroy(true);
  }

  // 获取目标DOM元素
  const targetElement = document.querySelector('.sphere-face-2d');
  if (!targetElement) {
    console.error("Target element not found");
    return;
  }

  // 清空目标元素
  targetElement.innerHTML = '';

  // 创建PIXI应用
  app = new PIXI.Application({
    width: props.renderParams.width,
    height: props.renderParams.height,
    backgroundColor: 0xffffff,
    antialias: true
  });

  // 手动将canvas添加到目标元素
  targetElement.appendChild(app.view);

  // 创建主容器
  container = new PIXI.Container();
  app.stage.addChild(container);

  // 重置传感器编号计数器
  sensorCounter = 1;

  // 绘制网格
  console.log("drawGrid")
  drawGrid();

  // 添加初始示例传感器
  addInitialSensors();
};

// 绘制网格和刻度
const drawGrid = () => {
  if (!app || !container) return;

  // 清空容器
  container.removeChildren();

  const { cellWidth, cellHeight } = calculateGridSize();
  const availableWidth = props.renderParams.width - 2 * padding;
  const availableHeight = props.renderParams.height - 2 * padding;

  // 绘制网格线
  const gridGraphics = new PIXI.Graphics();
  // 加粗网格线使其更明显
  gridGraphics.lineStyle(2, 0xbbbbbb);

  // 垂直线（经度线）
  for (let i = 0; i <= gridSize; i++) {
    const x = padding + i * cellWidth;
    gridGraphics.moveTo(x, padding);
    gridGraphics.lineTo(x, padding + availableHeight);

    // 偶数位显示经度刻度
    if (i % 2 === 0) {
      const longitude = Math.round((i / gridSize) * 360);
      const text = new PIXI.Text(longitude.toString(), {
        fontSize: 12,
        fill: 0x333333,
        align: 'right'
      });
      text.x = x - text.width / 2;
      text.y = padding - 20;
      container.addChild(text);
    }
  }

  // 水平线（纬度线）
  for (let i = 0; i <= gridSize; i++) {
    const y = padding + i * cellHeight;
    gridGraphics.moveTo(padding, y);
    gridGraphics.lineTo(padding + availableWidth, y);

    // 偶数位显示纬度刻度
    if (i % 2 === 0) {
      const latitude = Math.round((i / gridSize) * 180);
      const text = new PIXI.Text(latitude.toString(), {
        fontSize: 12,
        fill: 0x333333
      });
      text.x = padding - text.width - 5;
      text.y = y - text.height / 2;
      container.addChild(text);
    }
  }

  container.addChild(gridGraphics);

  // 绘制边界框使画布区域更清晰
  const borderGraphics = new PIXI.Graphics();
  borderGraphics.lineStyle(2, 0x000000);
  borderGraphics.drawRect(padding, padding, availableWidth, availableHeight);
  container.addChild(borderGraphics);

  // 重新添加已有的物体和点
  redrawObjects();

  // 确保应用渲染
  if (app) {
    app.renderer.render(app.stage);
  }
};

// 重新绘制所有传感器和点
const redrawObjects = () => {
  if (!container) return;

  // 创建新的物体数组，避免重复添加
  const objectsToRedraw = [...objects.value];
  objects.value = [];

  // 重置计数器，保留原有编号
  sensorCounter = 1;

  // 先找出最大编号，确保后续添加的传感器编号连续
  const maxSensorId = objectsToRedraw
    .filter(obj => obj.type === 'sensor' && obj.id)
    .reduce((max, obj) => Math.max(max, obj.id || 0), 0);

  if (maxSensorId > 0) {
    sensorCounter = maxSensorId + 1;
  }

  // 重新添加所有物体
  objectsToRedraw.forEach(obj => {
    if (obj.type === 'sensor') {
      addSensor(obj.longitude, obj.latitude);
    } else {
      addPoint(obj.longitude, obj.latitude);
    }
  });
};

// 坐标转换：经纬度到画布坐标
const geoToCanvas = (longitude: number, latitude: number) => {
  const { cellWidth, cellHeight } = calculateGridSize();
  // 确保经纬度在有效范围内
  const normalizedLongitude = ((longitude % 360) + 360) % 360;
  const normalizedLatitude = Math.max(0, Math.min(180, latitude));

  const x = padding + (normalizedLongitude / 360) * gridSize * cellWidth;
  const y = padding + (normalizedLatitude / 180) * gridSize * cellHeight;

  return { x, y };
};

// 添加传感器/点到画布
const addObjectToCanvas = (longitude: number, latitude: number, type: 'sensor' | 'point', id?: number) => {
  if (!container || !app) return null;

  const { x, y } = geoToCanvas(longitude, latitude);
  const graphic = new PIXI.Graphics();
  let label: PIXI.Text | undefined;
  let tooltip: PIXI.Container | undefined;

  if (type === 'sensor') {
    // 蓝色小方块 - 增大尺寸确保可见
    graphic.beginFill(0x1E90FF);
    graphic.drawRect(-5, -5, 10, 10);
    graphic.endFill();

    // 为传感器添加编号标签
    label = new PIXI.Text(id?.toString() || '', {
      fontSize: 12,
      fill: 0x000000,
      fontWeight: 'bold'
    });
    label.x = x + 8; // 标签显示在物体右侧
    label.y = y - 6; // 垂直居中对齐
    container.addChild(label);

    // 创建tooltip容器
    tooltip = new PIXI.Container();
    tooltip.visible = false;

    // 添加tooltip背景
    const tooltipBg = new PIXI.Graphics();
    tooltipBg.beginFill(0x000000, 0.8);
    tooltipBg.drawRoundedRect(0, 0, 120, 40, 5);
    tooltipBg.endFill();
    tooltip.addChild(tooltipBg);

    // 添加tooltip文本
    const tooltipText = new PIXI.Text(`传感器 ${id}\n经度: ${longitude}\n纬度: ${latitude}`, {
      fontSize: 9,
      fill: 0xffffff
    });
    tooltipText.x = 10;
    tooltipText.y = 5;
    tooltip.addChild(tooltipText);

    tooltip.x = x + 15;
    tooltip.y = y - 30;
    container.addChild(tooltip);

    // 设置交互属性
    graphic.interactive = true;
    graphic.buttonMode = true;

    // 添加鼠标悬浮事件
    graphic.on('mouseover', () => {
      if (tooltip) {
        tooltip.visible = true;
        app?.renderer.render(app.stage);
      }
    });

    graphic.on('mouseout', () => {
      if (tooltip) {
        tooltip.visible = false;
        app?.renderer.render(app.stage);
      }
    });
  } else {
    // 红色小圆点 - 增大尺寸确保可见
    graphic.beginFill(0xFF3333);
    graphic.drawCircle(0, 0, 2);
    graphic.endFill();
  }

  graphic.x = x;
  graphic.y = y;
  container.addChild(graphic);

  // 确保应用渲染
  app.renderer.render(app.stage);

  return { graphic, label, tooltip };
};

// 添加传感器（蓝色方块）
const addSensor = (longitude: number, latitude: number) => {
  const existingIndex = objects.value.findIndex(
    obj => obj.longitude === longitude && obj.latitude === latitude && obj.type === 'sensor'
  );

  if (existingIndex === -1) {
    const currentId = sensorCounter++;
    const result = addObjectToCanvas(longitude, latitude, 'sensor', currentId);
    if (result && result.graphic) {
      objects.value.push({
        longitude,
        latitude,
        type: 'sensor',
        graphic: result.graphic,
        label: result.label,
        tooltip: result.tooltip,
        id: currentId
      });
    }
  }
};

// 添加点（红色圆点）
const addPoint = (longitude: number, latitude: number) => {
  const existingIndex = objects.value.findIndex(
    obj => obj.longitude === longitude && obj.latitude === latitude && obj.type === 'point'
  );

  if (existingIndex === -1) {
    const graphic = addObjectToCanvas(longitude, latitude, 'point');
    if (graphic) {
      objects.value.push({ longitude, latitude, type: 'point', graphic });
    }
  }
};

// 移除传感器或点
const removeObject = (longitude: number, latitude: number, type?: 'sensor' | 'point') => {
  const indicesToRemove: number[] = [];

  objects.value.forEach((obj, index) => {
    if (obj.longitude === longitude && obj.latitude === latitude && (!type || obj.type === type)) {
      // 移除鼠标事件监听
      if (obj.graphic) {
        obj.graphic.removeAllListeners();
        if (container) {
          container.removeChild(obj.graphic);
        }
      }
      // 移除标签
      if (obj.label && container) {
        container.removeChild(obj.label);
      }
      // 移除tooltip
      if (obj.tooltip && container) {
        container.removeChild(obj.tooltip);
      }
      indicesToRemove.push(index);
    }
  });

  // 从后往前移除，避免索引变化问题
  indicesToRemove.sort((a, b) => b - a).forEach(index => {
    objects.value.splice(index, 1);
  });
};

// 添加初始示例传感器
const addInitialSensors = () => {
  // 添加蓝色方块示例（传感器）
  addSensor(90, 45);     // 经度90，纬度45
  addSensor(180, 90);    // 经度180，纬度90
  addSensor(270, 135);   // 经度270，纬度135
  addSensor(45, 30);     // 经度45，纬度30
  addSensor(225, 60);    // 经度225，纬度60

  // 添加红色圆点示例
  addPoint(0, 0);       // 经度0，纬度0
  addPoint(120, 75);    // 经度120，纬度75
  addPoint(240, 120);   // 经度240，纬度120
  addPoint(315, 150);   // 经度315，纬度150
  addPoint(60, 10);     // 经度60，纬度10

  console.log('添加了初始示例传感器');
};

// 暴露方法给父组件
defineExpose({
  addSensor,
  addPoint,
  removeObject
});

// 监听参数变化
watch(() => props.locateSetting, (newVal) => {
  console.log('SphereFace2D - Locate setting changed:', newVal);
  // 2D视图对locateSetting变化的处理逻辑
}, { deep: true, immediate: true });

// 监听渲染参数变化，重新初始化PIXI
watch(() => props.renderParams, (newVal) => {
  console.log('SphereFace2D - Render params changed:', newVal);
  nextTick(() => {
    initPIXI();
  });
}, { deep: true, immediate: true });

watch(() => props.searchParams, (newVal) => {
  console.log('SphereFace2D - Search params changed:', newVal);
  // 2D视图对searchParams变化的处理逻辑
}, { deep: true, immediate: true });

// 清理资源和事件监听器
const cleanup = () => {
  if (app) {
    // 移除所有物体的事件监听
    objects.value.forEach(obj => {
      if (obj.graphic) {
        // 安全地移除事件监听器，避免方法不存在的错误
        if (typeof obj.graphic.removeAllListeners === 'function') {
          obj.graphic.removeAllListeners();
        }
      }
    });

    // 销毁应用
    app.destroy(true);
    app = null;
    container = null;
    objects.value = [];
  }
};

onMounted(() => {
  console.log('SphereFace2D component mounted');
  nextTick(() => {
    initPIXI();
  });
});

onUnmounted(() => {
  console.log('SphereFace2D component unmounted');
  cleanup();
});
</script>

<template>
  <div class="sphere-face-2d" :style="{ width: renderParams.width + 'px', height: renderParams.height + 'px' }"></div>
</template>

<style scoped lang="scss">
.sphere-face-2d {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.sphere-face-2d canvas {
  display: block;
}
</style>
